package cxt.cn.community.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSSClient;
import cxt.cn.community.utils.CommonResult;
import cxt.cn.community.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * @author hj（BaridHu）
 */

@Slf4j
@Api(value = "file", tags = {"文件控制层"})
@RequestMapping("/api/file")
@RestController
public class FileController {

    @Value("${aliyun.oss.maxSize}")
    private int maxSize;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrefix;

    @Resource
    private OSSClient ossClient;


    @ApiOperation(value = "文件上传OSS接口")
    @PostMapping("upload")
    public CommonResult uploadToOSS(MultipartFile file) {
        String url = "";
        try {
            InputStream inputStream = file.getInputStream();
            String objectName =  getObjectName(file);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
            url = formatPath(objectName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.success(url);
    }

    private String getObjectName(MultipartFile file) {
        // 文件后缀
        String suffixName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffixName;
        // 完整路径
        return dirPrefix + "images/" + DateUtil.today() + "/" + fileName;
    }

    private String formatPath(String objectName){
        return "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + objectName;
    }
}
